<template>
  <div class="myMessage">
    <van-nav-bar
      title="我的消息"
      left-text=""
      left-arrow
      @click-left="toLastPage"
      @click-right="onClickRight"
    >
      <template #right>
        <div v-if="isReadArrLength">全部已读</div>
        <div v-if="!isReadArrLength" class="isRead" style="color: #ccc">
          <button disabled style="border: 0px; background-color: transparent">
            全部已读
          </button>
        </div>
      </template>
    </van-nav-bar>
    <!-- 消息列表 -->
    <van-cell-group inset>
      <van-cell
        :title="list[index].content"
        is-link
        v-for="(item, index) in list"
        @click="afterRead(index)"
        :key="index"
      >
        <!-- 使用 title 插槽来自定义标题 -->
        <template #right-icon>
          <div class="circle" v-if="!list[index].isRead"></div>
          <i class="iconfont iconicon_more"></i>
        </template>
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { systemMessagesGet, systemMessagesRead } from '@/api/my.js'
export default {
  name: 'MyMessage',
  data () {
    return {
      list: [],

      isReadArrLength: ''
    }
  },
  created () {
    this.$toast.loading({ message: '加载中' })
    this.messageInfo()
  },
  methods: {
    async messageInfo () {
      const res = await systemMessagesGet()
      this.list = res.data.reverse()
      this.$nextTick(() => {
        this.$toast.clear()
      })
      // 设置未读列表
      const isReadArr = this.list.filter((v) => {
        return !v.isRead
      })
      // 把未读列表长度设置给isReadArr
      this.isReadArrLength = isReadArr.length
    },

    toLastPage () {
      const lastPage = this.$route.params.lastPage || '/'
      this.$router.push(lastPage)
    },
    // 点击消息列表更改该项已读效果
    async afterRead (index) {
      const ids = this.list[index].id
      await systemMessagesRead({ ids: [ids] })
      this.messageInfo()
    },
    // 全部已读
    async onClickRight () {
      const res = this.list.filter((v) => {
        return !v.isRead
      })
      const arr = res.map((v) => {
        return v.id
      })
      await systemMessagesRead({ ids: arr })
      this.messageInfo()
    }
  }
}
</script>

<style lang="less" scoped>
::v-deep .van-nav-bar__text {
  color: #000;
}
::v-deep .van-nav-bar__right {
  color: #71b6fc;
}
::v-deep .iconicon_more {
  font-size: 12px;
  color: #7a7c8f;
}
.van-cell--clickable {
  position: relative;
}
.circle {
  width: 20px;
  height: 20px;
  background: #ff4949;
  border-radius: 50%;
  position: absolute;
  margin: auto;
  top: 0;
  right: 80px;
  bottom: 0;
}
</style>
